/*
 * Copyright (C) 2008 Matt Falkoski
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.falko.android.raven.settings;

import java.io.File;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.falko.android.raven.R;

public class ImagePreviewPreference extends Preference implements
		SharedPreferences.OnSharedPreferenceChangeListener {

	private final String TAG = getClass().getName();
	private ImageView imageView_;

	public ImagePreviewPreference(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public ImagePreviewPreference(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);

	}

	@Override
	protected View onCreateView(ViewGroup parent) {

		LinearLayout layout = null;

		try {
			LayoutInflater mInflater = (LayoutInflater) getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			layout = (LinearLayout) mInflater.inflate(
					R.layout.image_preview_preference, parent, false);
		} catch (Exception e) {
			Log.e(TAG, "Error creating color chooser preference", e);
		}
		imageView_ = (ImageView) layout.findViewById(R.id.image_preview);
		return layout;
	}
	
	@Override
	protected void onBindView(View view) {
		super.onBindView(view);
		String imagePath = getSharedPreferences().getString("IMAGE_PATH", null);
		getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
		imageView_.setScaleType(ImageView.ScaleType.FIT_CENTER);
		if (imagePath != null) {
			loadImage(imagePath);
		}
	}

	@Override
	protected Object onGetDefaultValue(TypedArray ta, int index) {
		return ta.getString(index);
	}

	@Override
	protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
		// do nothing
	}

	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		if (key.equalsIgnoreCase("IMAGE_PATH")) {
			String imagePath = sharedPreferences.getString("IMAGE_PATH", null);

			if (imagePath != null) {
				loadImage(imagePath);
			}
		}
	
	}
	
	@Override
	protected void onPrepareForRemoval() {
		super.onPrepareForRemoval();
		getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
	}
	
	private boolean loadImage(String path) {

		Bitmap bg = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		int sampleSize = 1;
		if (new File(path).exists()) {
			while (bg == null) {
				options.inSampleSize = sampleSize;
				try {
					bg = BitmapFactory.decodeFile(path, options);
				} catch (OutOfMemoryError e) {
					bg = null;
					sampleSize++;
				} catch (Exception e) {
					return false;
				}
			}
		} else {
			return false;
		}


		float imageWidth = 200;
		float imageHeight = ((imageWidth / bg.getWidth()) * bg.getHeight());

		imageView_.setImageBitmap(Bitmap.createScaledBitmap(bg,
				(int) imageWidth, (int) imageHeight, false));
		bg.recycle();
		return true;
	}
}
